package com.biao.java8.demo;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class TestLambda2 {
    /*
         可以使用lambda表达式的写法：四大内置核心的函数式接口
        1,  Consumer<T>: 消费型接口
             void accept(T t);      有参数无返回值
        2,  Supplier<T>: 供给型接口
             T get();        无参数有返回值
        3,  Function<T, R>: 函数型接口
             R apply(T t);      有参数有返回值
        4,  Predicate<T>:  断言型接口
             boolean test(T t);
         */
    public static void main(String[] args) {
        // Consumer<T>: 消费型接口
        happy(10000, m -> System.out.println("大保健消费￥" + m + "元"));

        // Supplier<T>: 供给型接口
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        numList.forEach(System.out::println);

        // Function<T, R>: 函数型接口
        String strHandler = strHandler("\t\t\t\t\tlalala", s -> s.trim());
        System.out.println(strHandler);
        String substring = strHandler("lalala", s -> s.substring(2));
        System.out.println(substring);

        // Predicate<T>:  断言型接口
        List<String> strings = Arrays.asList("123", "1234", "12345");
        List<String> stringList = filterStr(strings, s -> s.length() > 3);
        stringList.forEach(System.out::println);
    }

    static void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    static List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;
    }

    static String strHandler(String s, Function<String, String> function) {
        return function.apply(s);
    }

    static List<String> filterStr(List<String> list, Predicate<String> predicate) {
        ArrayList<String> strList = new ArrayList<>();
        for (String s : list) {
            if (predicate.test(s)) {
                strList.add(s);
            }
        }
        return strList;
    }
}
